#include "mgame.h"

#include "mutil.h"

MGame::MGame(QObject *parent) :
    QObject(parent)
{
    state = TO_CHOOSE_YOUR_CARD;
    for (int i = 0; i <= 12; i++) {
        OutCardRest[i] = 4;
        MyCardRest[i] = 0;
    }
    OutCardRest[13] = OutCardRest[14] = 1;
    MyCardRest[13] = MyCardRest[14] = 0;
    for (int i = 0; i < 3; i++)
        HandRest[i] = 17;
}

QString MGame::setYourCards(std::multiset<MCard> cards)
{
    if (state != TO_CHOOSE_YOUR_CARD)
        MUtil::debugAndExit(MUtil::getStr("err_game") + " TO_CHOOSE_YOUR_CARD");

    if (cards.size() != 17)
    {
        return MUtil::getStr("err_initcardnum");
    }

    foreach (MCard a, cards) {
        MyCardRest[a.id]++;
        OutCardRest[a.id]--;
    }
    state = TO_CHOOSE_EVIL;
    return "";

}

QString MGame::setEvilID(MGame::PlayerID id)
{

    if (state != TO_CHOOSE_EVIL)
        MUtil::debugAndExit(MUtil::getStr("err_game") + " TO_CHOOSE_EVIL");

    HandRest[EVILID = id] += 3;
    state = TO_CHOOSE_EVIL_CARD;
    return "";
}

QString MGame::setEvilExtraCards(std::multiset<MCard> cards)
{
    if (state != TO_CHOOSE_EVIL_CARD)
        MUtil::debugAndExit(MUtil::getStr("err_game") + " TO_CHOOSE_EVIL_CARD");

    if (cards.size() != 3)
    {
        return MUtil::getStr("err_evilcardnum");
    }

    int cnt = 0;
    foreach (MCard a, cards)
    {
        EVILCard[cnt++] = a;
        if (EVILID == YOU)
        {
            MyCardRest[a.id]++;
            OutCardRest[a.id]--;
        }
    }
    state=TO_CHOOSE_TURN_CARD;
    nowPlayer = EVILID;
    return "";
}
/*for (multiset<MCard>::iterator it = cards.begin(); it != cards.end(); ++it) {
    MCard a = *it;
    // 处理a
}*/

QString MGame::play(std::multiset<MCard> cards)
{
    int tmprec[20], cnt = 0;
    foreach (MCard a, cards) {
        tmprec[++cnt] = a.id;
    }

    if (nowPlayer == 1) {
        for (int i = 1; i <= cnt; i++)
            MyCardRest[tmprec[i]]--;
    }
    else {
        for (int i = 1; i <= cnt; i++)
            OutCardRest[tmprec[i]]--;
    }
    HandRest[nowPlayer] -= cnt;
    if (HandRest[nowPlayer] <= 0)
    {
        state = END;
        emit gameOver(nowPlayer == YOU || (nowPlayer != EVILID && YOU != EVILID));
    }
    ++nowPlayer;
    if (nowPlayer > 2)
        nowPlayer = 0;
    return "";
}

int MGame::getPlayerMaxRemain(MGame::PlayerID id, MCard card)
{
    if (id == YOU)
        return MyCardRest[card.id];
    if (id == EVILID)
        return OutCardRest[card.id];
    int res = OutCardRest[card.id];
    if (YOU != EVILID)
        for (int i = 0; i < 3; ++i)
            if (EVILCard[i].id == card.id)
                --res;
    return res;
}

int MGame::getOutRemain(MCard card)
{
    return OutCardRest[card.id];
}

int MGame::getHandRemain(PlayerID id)
{
    return HandRest[id];
}

MGame::PlayerID MGame::getTurn()
{
    return (PlayerID)nowPlayer;
}

